<?php

class TkApp
{

    /**
     *
     * @var TkView
     */
    private $view;
    private $projects = array();

    /**
     *
     * @var TkProject 
     */
    private $project = null;
    private $actions = array('synchronize');
    private $messages = array();
    private $errors = array();
    private $valid = true;

    public function __construct()
    {
        $this->view = new TkView();

        $this->validate();
        $this->initProjects();
        $this->runAction();
    }

    private function validate()
    {
        $extensions = get_loaded_extensions();

        if (!in_array('gettext', $extensions))
        {
            $this->errors[] = 'Extension "<b>gettext</b> for php is missing, please install it';
        }

        if (!in_array('curl', $extensions))
        {
            $this->errors[] = 'Extension "<b>curl</b> for php is missing, please install it';
        }
    }

    private function initProjects()
    {
        $config = parse_ini_file('application/config.ini', true);

        foreach ($config as $key => $data)
        {
            $this->projects[$key] = new TkProject($data);
        }

        if (isset($_REQUEST['project']) && key_exists($_REQUEST['project'], $this->projects))
        {
            $this->project = $this->projects[$_REQUEST['project']];
        }
    }

    public static function listSystemLocales()
    {
        ob_start();
        system('locale -a');
        $str = ob_get_contents();
        ob_end_clean();
        return explode("\n", trim($str));
    }

    private function runAction()
    {
        if (!is_null($this->project))
        {
            if ($this->project->isValid())
            {
                if (isset($_REQUEST['action']) && in_array($_REQUEST['action'], $this->actions))
                {
                    $action = $_REQUEST['action'];
                    $this->project->$action();
                    $this->errors = array_merge($this->errors, $this->project->errors);
                    $this->messages = array_merge($this->messages, $this->project->messages);
                }
            }
            else
            {
                $this->message = 'Action was <b>NOT</b> realized, please check errors.';
            }
        }
    }

    public function run()
    {
        $this->view->errors = $this->errors;
        $this->view->messages = $this->messages;
        $this->view->projects = $this->projects;
        $this->view->locales = $this->listSystemLocales();
        $this->view->render();
    }
}
